// 这是通过content_script中创建script标签的方式
// 直接嵌入到当前html文档的js文件
// 可以实现dom绑定事件去操作content_script中的方法

var bookMarks;
var data;
var position = window.location.host;

function getData(student) {
    console.log(student)
    if(typeof student != 'undefined'){
        if(student[bookMarks.parentTitle]){
            return student[bookMarks.parentTitle][bookMarks.title] || [];
        }
        else return [];
    }
    else return [];
}
window.addEventListener("message", function(e) {
    if(e.data.type === 'allData'){
        bookMarks = e.data.info.togoBookmark;
        console.log(bookMarks);
        changeInputValue();

        data = getData(e.data.info.student);
        refreshDom();
        console.log(data);
    }
}, false);

function changeInputValue() {
    // $('#togo-name').text(bookMarks.parentTitle);
    // $('#togo-job').text(bookMarks.title);
    // $('#fileName').val(bookMarks.parentTitle+'-'+bookMarks.title);
    document.getElementById('togo-name').innerText = bookMarks.parentTitle;
    document.getElementById('togo-job').innerText = bookMarks.title;
    document.getElementById('fileName').value = bookMarks.parentTitle+'-'+bookMarks.title;
}

function createElements() {
    let tr = '';
    for(let i=0;i<data.length;i++){
        tr += '<tr>'+
            '<td>' +
            '<span class="del-data" data-dIndex="' + i + '">删除 </span>' +
            '</td>'+
            '<td class="do">'+
            '<span class="copy-data" data-cIndex="' + i + '"> 复制</span>' +
            '<span>'+(i+1)+'</span></td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="company">'+(data[i].company?data[i].company:'无')+'</span>'+
            '<input type="text" value="'+data[i].company+'">' +
            '</td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="job">'+(data[i].job?data[i].job:'无')+'</span>'+
            '<input type="text" value="'+data[i].job+'">' +
            '</td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="address">'+(data[i].address?data[i].address:'无')+'</span>'+
            '<input type="text" value="'+data[i].address+'">' +
            '</td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="salary">'+(data[i].salary?data[i].salary:'无')+'</span>'+
            '<input type="text" value="'+data[i].salary+'">' +
            '</td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="time">'+(data[i].time?data[i].time:'无')+'</span>'+
            '<input type="text" value="'+data[i].time+'">' +
            '</td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="url">'+(data[i].url?data[i].url:'无')+'</span>'+
            '<input type="text" value="'+data[i].url+'">' +
            '</td>'+
            '<td>' +
            '<span data-eIndex="' + i + '" data-key="tip">'+(data[i].tip?data[i].tip:'无')+'</span>'+
            '<input type="text" value="'+data[i].tip+'">' +
            '</td>'+
            '</tr>';
    }
    return tr;
}// 将全局变量 data 处理为对应的 table 元素组成的 jsx 字符串

function refreshDom() {
    // $('#togo-table tbody').html(createElements());
    document.querySelector('#togo-table tbody').innerHTML = createElements();
}// 刷新表格的Dom 实现更新数据


document.querySelector('.get-data').onclick = function () {
    // 获得爬取的数据
    let pageData = crawlDataFunction[position]();

    if(!pageData){return;}

    // 存储到data
    window.postMessage({type: 'update',info: pageData}, '*');
    data.push(pageData);

    alert('抓取成功');
    // 刷新Dom 更新数据
    refreshDom();
};// 爬取数据 按钮点击事件

document.querySelector('#getExcel').onclick = function () {
    tableToExcel(data);
};// 导出EXCEL 按钮点击事件

// 事件代理
// 实现效果： 点击删除按钮，将对应下标传入 deleteData 函数
//           点击复制按钮，将对应下标传入 copyData 函数
document.querySelector('#togo-table').onclick = function (event) {
    let element = event.target || null;
    if(element.getAttribute('data-dIndex'))
        deleteData(element.getAttribute('data-dIndex'));
    else if(element.getAttribute('data-cIndex'))
        copyOneData(element.getAttribute('data-cIndex'))
};
// 实现效果： 双击当前td 显示输入框
document.querySelector('#togo-table').addEventListener('dblclick',function (event) {
    let element = event.target || null;
    if(element.getAttribute('data-eIndex')){
        element.nextElementSibling.style.display = 'block';
        element.nextElementSibling.focus();
        element.nextElementSibling.onblur = function () {
            this.style.display = 'none';
            editData(element.getAttribute('data-eIndex'), element.getAttribute('data-key'), this.value);
            element.innerText = this.value?this.value:'无';
        };
    }
});

function trim(str) {
    return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}// 去除前后空格
var crawlDataFunction = {
    'www.lagou.com': function () {
        let pageData = {};
        if($('.job_company_content .fl-cn').text() == ''){
            return false;
        }
        pageData.company = $('.job_company_content .fl-cn').text();
        pageData.address = $('.position-content .job_request p').eq(0).children().eq(1).text();
        pageData.address = pageData.address.split('/')[1];
        pageData.job = $('.position-content .job-name .name').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.salary').innerText || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 拉钩   爬取当前网页的数据
    'www.zhipin.com': function () {
        let pageData = {};
        if($('.job-banner .name h1').text() == ''){
            return false;
        }
        pageData.company = $('.job-sec .name').text();
        pageData.address = $('.job-banner .info-primary p')[0].firstChild.data;
        pageData.job = $('.job-banner .name h1').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.salary').innerText || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// BOSS
    'jobs.51job.com': function () {
        let pageData = {};
        if($('.tHjob .cn h1').text() == ''){
            return false;
        }
        pageData.company = $('.tHjob .catn').text();
        pageData.address = $('.tHjob .msg')[0].firstChild.data;
        pageData.job = $('.tHjob .cn h1').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.tHjob .cn strong').innerText || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 前程无忧
    'jobs.zhaopin.com': function () {
        let pageData = {};
        if(document.querySelector('.summary-plane__title').innerText == ''){
            return false;
        }
        pageData.company = document.querySelector('.company__title').innerText;
        pageData.address = document.querySelector('.summary-plane__info a').innerText;
        pageData.job = document.querySelector('.summary-plane__title').innerText;
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.summary-plane__salary').innerText || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 智联
    'www.liepin.com': function () {
        let pageData = {};
        if($('.title-info h1').text() == ''){
            return false;
        }
        pageData.company = $('.title-info h3 a').text();
        pageData.address = $('.job-item .basic-infor a').text();
        pageData.job = $('.title-info h1').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.job-item-title').childNodes[0].textContent || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 猎聘
    'campus.liepin.com': function () {
        let pageData = {};
        if($('.job-brief h1.job-name').text() == ''){
            return false;
        }
        pageData.company = $('.company-address a.company-name').text();
        pageData.address = $('.job-brief .job-info span.where').text();
        pageData.job = $('.job-brief h1.job-name').text();
        pageData.url = window.location.href;
        pageData.salary = '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 猎聘校园
    'shixi.xiaozao.org': function () {
        let pageData = {};
        if(document.getElementsByClassName('title')[0].innerText == ''){
            return false;
        }
        pageData.company = document.getElementsByClassName('my-text-center')[0].children[1].textContent;
        pageData.address = document.getElementsByClassName('ant-row-flex-space-between')[2].children[0].children[1].textContent;
        pageData.job = document.getElementsByClassName('title')[0].innerText;
        pageData.url = window.location.href;
        pageData.salary = document.querySelectorAll('.ant-row-flex.ant-row-flex-middle')[4].textContent || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 小灶实习
    'www.shixiseng.com': function () {
        let pageData = {};
        if($('.new_job_name').text() == ''){
            return false;
        }
        pageData.company = $('.job-com .com-name').text();
        pageData.address = $('.job_position').text();
        pageData.job = $('.new_job_name').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.job_money.cutom_font').textContent || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 实习僧
    'sxxx.haitou.cc': function () {
        let pageData = {};
        if($('.detail-top-msg h4').text() == ''){
            return false;
        }
        pageData.company = $('.detail-company-logo p').text();
        pageData.address = $('.detail-top-msg li').eq(0).text();
        pageData.job = $('.detail-top-msg h4').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelectorAll('.detail-top-msg li')[3].textContent || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 海投实习网
    'job.liuxuehr.com': function () {
        let pageData = {};
        if($('.j-n-txt').text() == ''){
            return false;
        }
        pageData.company = $('.comname .line_substring').text();
        pageData.address = $('.add').text().split('工作地点')[1];
        pageData.job = $('.j-n-txt').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.wage').innerText || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 留学生人才网
    'job.dajie.com': function () {
        let pageData = {};
        if($('.job-msg .job-name').text() == ''){
            return false;
        }
        pageData.company = $('.i-corp-base-info .title').text();
        pageData.address = $('.job-msg .ads').text();
        pageData.job = $('.job-msg .job-name').text();
        pageData.url = window.location.href;
        pageData.salary = document.querySelector('.job-money').innerText || '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 大街校园网
    'xiaoyuan.zhaopin.com': function () {
        let pageData = {};
        if(document.querySelector('#JobName').innerText == ''){
            return false;
        }
        pageData.company = document.querySelector('#jobCompany').innerText;
        pageData.address = document.querySelector('#currentJobCity').innerText;
        pageData.job = document.querySelector('#JobName').innerText;
        pageData.url = window.location.href;
        pageData.salary = '面议';
        pageData.time = '';
        pageData.tip = '';

        for(let key in pageData){
            // 去除前后空格
            pageData[key] = trim(pageData[key]);
        }
        return pageData;
    },// 智联校招
};

function editData(index, key, value) {
    window.postMessage({type: 'edit',info: {index: index, key: key, value: value}}, '*');
    data[index][key] = value;
    console.log(data);
}

function deleteData(index) {
    window.postMessage({type: 'delete',info: index}, '*');
    if(index === 'children'){
        data = [];
    }else{
        data.splice(index, 1);
    }
    refreshDom();
}// 删除对应下标index的data，并更新数据

function copyOneData(index) {
    let text = (index-0+1) +'\t'+ data[index].company +'\t'+ data[index].address +'\t'+ data[index].job +'\t'+ data[index].url +'\t ';
    let copyThat = document.getElementById('copyThat');
    copyThat.innerText = text;
    copyThat.select();
    document.execCommand("copy");
    alert("复制成功");
}

function tableToExcel(jsonData){
    //列标题，逗号隔开，每一个逗号就是隔开一个单元格
    let str = `序号,公司,岗位名称,工作地点,薪资水平,投递截止时间,网页链接,备注\n`;
    //增加\t为了不让表格显示科学计数法或者其他格式
    for(let i = 0 ; i < jsonData.length ; i++ ){
        str+=`${(i+1) + '\t'},`;
        str+=`${jsonData[i]['company'] + '\t'},`;
        str+=`${jsonData[i]['job'] + '\t'},`;
        str+=`${jsonData[i]['address'] + '\t'},`;
        str+=`${jsonData[i]['salary'] + '\t'},`;
        str+=`${jsonData[i]['time'] + '\t'},`;
        str+=`${jsonData[i]['url'] + '\t'},`;
        str+=`${jsonData[i]['tip'] + '\t'},`;
        str+='\n';
    }
    //encodeURIComponent解决中文乱码
    let url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    //通过创建a标签实现
    var link = document.getElementById("getExcel");
    link.href = url;
    //对下载的文件命名
    link.download =  document.querySelector('#fileName').value + '.csv';

    // 点击下载之后清除当前学生+方向的数据
    deleteData('children');
}// 将传入的数据，生成.csv后缀的文件

window.postMessage({type: 'select',info: ''}, '*');
